package com.my.admin.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.admin.mapper.AdUserMapper;
import com.my.admin.service.AdUserService;
import com.my.model.admin.dtos.AdminLoginDto;
import com.my.model.admin.pojos.AdUser;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.utils.common.AppJwtUtil;
import com.my.utils.common.MD5Utils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 管理员登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        //1.校验参数
        if(dto == null || dto.getName().isEmpty() || dto.getPassword().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //2.根据用户名获取用户信息
        LambdaQueryWrapper<AdUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(lqw);
        
        //3.检验用户是否存在
        if(adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }
        
        //4.校验密码
        //4.1获取前端传过来的密码
        String originalPassword = dto.getPassword();
        //4.2获取盐
        String salt = adUser.getSalt();
        //4.3对前端密码进行MD5加密
        String md5Password = MD5Utils.encode(originalPassword + salt);
        //4.4获取数据库中的密码
        String password = adUser.getPassword();
        //4.5校验
        if(!md5Password.equals(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户密码错误");
        }

        //5.校验通过
        //5.1构建token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUser);

        return ResponseResult.okResult(map);
    }
}
